Using ‘applemusicpy’ to fetch albums from Apple Music

Using ‘applemusicpy’ to fetch albums from Apple Music

Hello, I'm Charu from Classmethod. In this short blog, we'll explore how the applemusicpy library can be used to search for albums on Apple Music using Python.

Applemusicpy is a Python wrapper for the Apple Music API. This makes it easy to make requests to the API and allows developers to easily interact with Apple Music's underlying database.

Let's get started!

To get started, Python and applemusicpy libraries must be installed. You can install the library using pip:

pip install applemusicpy

Additionally, you'll require an authentication key from Apple Music. This involves setting up a developer account with Apple, creating a MusicKit identifier, and generating a private key. You can refer this blog if you need guidance with setting up Apple Developer account.

The following code is to fetch the music albums from Apple-

import applemusicpy

with open('AuthKey_ABCDE12345.p8', 'r') as file:
    secret_key = file.read()
key_id = 'YOUR-KEY-ID'
team_id = 'YOUR-TEAM-ID'

am = applemusicpy.AppleMusic(secret_key, key_id, team_id)
results = am.search('charlie puth', types=['albums'], limit=10)

for item in results['results']['albums']['data']:
    print(item['attributes']['name'])

Code Explanation:

Remember to store the authentication key in your code directory.

  • The first step in our Python script involves reading the authentication key:
  • with open('AuthKey_LW5CUWL77V.p8', 'r') as file:
        secret_key = file.read()

    This key is crucial for all your interactions with the API, ensuring your requests are authorized and secure.

  • We then initialise the AppleMusic instance with our secret key, key ID, and team ID, obtained during the setup process:
  • am = applemusicpy.AppleMusic(secret_key, key_id, team_id)
  • The search method allows us to specify the artist and the type of content we are looking for. In this case, we are interested in albums by Charlie Puth, and we limit our search to 10 results.

    Finally, we iterate over the search results and print the album names:

  • for item in results['results']['albums']['data']:
        print(item['attributes']['name'])

    This loop accesses each album in the returned data and prints its name.

    Conclusion:

    The applemusicpy library opens up a world of possibilities for interacting with Apple Music. From simple searches, like the one we performed for Charlie Puth's albums, to more complex data analysis and playlist creation, the integration of Python with Apple Music's API allows us to innovate in exciting new ways.

    Thank you for reading!

    Happy Learning:)

    Share this article

    facebook logohatena logotwitter logo

    © Classmethod, Inc. All rights reserved.